﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WPLottery.Resources;
using Microsoft.Phone.Scheduler;

using WPLottery.Model;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using Windows.Phone.Speech.Recognition;
using Windows.Phone.Speech.Synthesis;
using Windows.Phone.Speech.VoiceCommands;

namespace WPLottery
{
    public partial class MainPage : PhoneApplicationPage
    {
        SpeechRecognizerUI myRecognizer;
        //List<NumberRow> _numberRows = new List<NumberRow>();
        ObservableCollection<NumberRow> _numberRows = new ObservableCollection<NumberRow>();

        private bool m_buttonTapped = false;
        private NumberRow m_editing = null;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //_numberRows.Add(new NumberRow(10, 20, 30, 40, 50, 60));
            llsNumbers.ItemsSource = _numberRows;

            try
            {
                RestoreData();
            }
            catch
            {
            }

            // Sample code to localize the ApplicationBar
            BuildLocalizedApplicationBar();

            myRecognizer = new SpeechRecognizerUI();
            
        }

        //private int CheckWinners(int n0, int n1, int n2, int n3, int n4, int n5)
        //{
        //    return _numberRows.Count(row => row.IsWinner(n0, n1, n2, n3, n4, n5));
        //}

        //private void Button_Click_1(object sender, RoutedEventArgs e)
        //{
        //    _numberRows.Add(new NumberRow(12, 23, 34, 45, 56, 67));
        //}

        //private void Button_Click_2(object sender, RoutedEventArgs e)
        //{
        //    _numberRows[0].Number0 = 33;
        //}

        //private void Grid_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        //{
        //}

        private void llsNumbers_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (m_buttonTapped)
            {
                if (MessageBoxResult.OK == MessageBox.Show("Are you sure?", "Delete Row", MessageBoxButton.OKCancel))
                {
                    _numberRows.Remove((NumberRow)((LongListSelector)sender).SelectedItem);
                    SaveData();
        }
            }
            else
            {
                m_editing = (NumberRow)((LongListSelector)sender).SelectedItem;
                TestTextBox0.Text = m_editing.Number0.ToString();
                TestTextBox1.Text = m_editing.Number1.ToString();
                TestTextBox2.Text = m_editing.Number2.ToString();
                TestTextBox3.Text = m_editing.Number3.ToString();
                TestTextBox4.Text = m_editing.Number4.ToString();
                TestTextBox5.Text = m_editing.Number5.ToString();
            }

            m_buttonTapped = false;
        }

        private void Button_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            m_buttonTapped = true;
        }

        // Sample code for building a localized ApplicationBar
        private void BuildLocalizedApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();

            // Create a new button and set the text value to the localized string from AppResources.
            ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("./Images/new.png", UriKind.Relative));
            appBarButton.Text = "New Play";                 //AppResources.AppBarButtonText;
            appBarButton.Click += appBarButton_Click;
            ApplicationBar.Buttons.Add(appBarButton);

            ApplicationBarIconButton appBarSpeakButton = new ApplicationBarIconButton(new Uri("./Images/microphonedark.png", UriKind.Relative));
            appBarSpeakButton.Text = "Speak";                 //AppResources.AppBarButtonText;
            appBarSpeakButton.Click += appBarSpeakButton_Click;
            ApplicationBar.Buttons.Add(appBarSpeakButton);

        }

        private async void appBarSpeakButton_Click(object sender, EventArgs e)
        {
            SpeechRecognitionUIResult recognitionResult = await myRecognizer.RecognizeWithUIAsync();
            if ((recognitionResult.RecognitionResult.TextConfidence == SpeechRecognitionConfidence.High) || (recognitionResult.RecognitionResult.TextConfidence == SpeechRecognitionConfidence.Medium))
            {
               // string inputNumber = Convert.ToUInt64(recognitionResult.RecognitionResult.Text).ToString();
                string inputNumber = recognitionResult.RecognitionResult.Text.Substring(0,12);
                if (inputNumber.Length == 12 )
                {
                    NumberRow row = new NumberRow(Convert.ToInt32(inputNumber.Substring(0, 2)), Convert.ToInt32(inputNumber.Substring(2, 2)), Convert.ToInt32(inputNumber.Substring(4, 2)), Convert.ToInt32(inputNumber.Substring(6, 2)), Convert.ToInt32(inputNumber.Substring(8, 2)), Convert.ToInt32(inputNumber.Substring(10, 2))) { Channel = App.CurrentChannel.ChannelUri.ToString() };
                    _numberRows.Add(row);
                    App.MobileService.GetTable<NumberRow>().InsertAsync(row);
                }
                else
                {
                    SpeechSynthesizer ss = new SpeechSynthesizer();
                    await ss.SpeakTextAsync("You spoke a " + inputNumber.Length + " digit number. Please speak twelve digits. If you have to say five, please say zero five");
                }
            }
        }

        void appBarButton_Click(object sender, EventArgs e)
        {
            //TestTextBox.Visibility = System.Windows.Visibility.Visible;
            NewRow.Visibility = System.Windows.Visibility.Visible;
        }

        private void Add_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (m_editing != null)
            {
                m_editing.Number0 = Convert.ToInt32(TestTextBox0.Text);
                m_editing.Number1 = Convert.ToInt32(TestTextBox1.Text);
                m_editing.Number2 = Convert.ToInt32(TestTextBox2.Text);
                m_editing.Number3 = Convert.ToInt32(TestTextBox3.Text);
                m_editing.Number4 = Convert.ToInt32(TestTextBox4.Text);
                m_editing.Number5 = Convert.ToInt32(TestTextBox5.Text);
                m_editing = null;
            }
            else
            {
                NumberRow row = new NumberRow(Convert.ToInt32(TestTextBox0.Text), Convert.ToInt32(TestTextBox1.Text), Convert.ToInt32(TestTextBox2.Text), Convert.ToInt32(TestTextBox3.Text), Convert.ToInt32(TestTextBox4.Text), Convert.ToInt32(TestTextBox5.Text)) { Channel = App.CurrentChannel.ChannelUri.ToString() };
                _numberRows.Add(row);
                App.MobileService.GetTable<NumberRow>().InsertAsync(row);
            }

            TestTextBox0.Text = "";
            TestTextBox1.Text = "";
            TestTextBox2.Text = "";
            TestTextBox3.Text = "";
            TestTextBox4.Text = "";
            TestTextBox5.Text = "";
            SaveData();
        }

        private void TestTextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            TextBox tbSender = sender as TextBox;
            

            if (tbSender != null && tbSender.Text.Length == 2)
            {
                if (tbSender.Name.Equals("TestTextBox0"))
                    TestTextBox1.Focus();
                else if (tbSender.Name.Equals("TestTextBox1"))
                    TestTextBox2.Focus();
                else if (tbSender.Name.Equals("TestTextBox2"))
                    TestTextBox3.Focus();
                else if (tbSender.Name.Equals("TestTextBox3"))
                    TestTextBox4.Focus();
                else if (tbSender.Name.Equals("TestTextBox4"))
                    TestTextBox5.Focus();
            }
        }

        private void SaveData()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream f = new IsolatedStorageFileStream("data", System.IO.FileMode.Create, System.IO.FileAccess.Write, isf))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<NumberRow>));

                    serializer.Serialize(f, _numberRows);
                }
            }
        }

        private void RestoreData()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.FileExists("data"))
                {
                    using (IsolatedStorageFileStream f = new IsolatedStorageFileStream("data", System.IO.FileMode.Open, System.IO.FileAccess.Read, isf))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<NumberRow>));

                        ObservableCollection<NumberRow> temp = (ObservableCollection<NumberRow>)serializer.Deserialize(f);
                        foreach (NumberRow nr in temp)
                        {
                            _numberRows.Add(nr);
                        }
                    }
                }
            }
        }
    }
}